import express from 'express';
import cors from 'cors';
import { config } from 'dotenv';
import { router as drawingRouter } from './routes/drawing.js';

// 加载环境变量
config();

const app = express();
const port = process.env.PORT || 3000;

// 中间件配置
app.use(cors({
  origin: 'http://localhost:5173',
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type']
}));
app.use(express.json());

// 路由配置
app.use('/api/drawing', drawingRouter);

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// 错误处理中间件
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error(err.stack);
  res.status(500).json({ error: '服务器内部错误' });
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});